<template>
  <div class="container-xl">
    <div class="row">
      <div class="col">团队任务</div>
      <div class="col text-right">
        <el-button v-if="isAdmin" @click="dialogTableVisible = true">+ 新增任务</el-button>
      </div>
    </div>
    <hr />
    <el-dialog title="创建通知" v-model="dialogTableVisible">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm1" label-width="100px" class="demo-ruleForm">
        <el-form-item label="通知人" prop="user">
          <el-cascader v-model="ruleForm.teamtaskuser" :options="group" :props="{
            multiple: true,
          }" collapse-tags clearable :show-all-levels="false"></el-cascader>
        </el-form-item>
        <el-form-item label="通知内容：" prop="context">
          <el-input type="textarea" v-model="ruleForm.context"></el-input>
        </el-form-item>
        <el-form-item label="跳转链接：" prop="info">
          <el-input v-model="ruleForm.info"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogTableVisible = false">取 消</el-button>
          <el-button type="success" @click="submitForm()">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <div v-if="task?.count">
      <el-table :data="task.rows" border style="width: 100%" height="50vh">
        <el-table-column type="expand">
          <template #default="{ row, index }">
            <ul class="list-group" v-if="row.teamtaskuser.length">
              <li class="
                  list-group-item
                  d-flex
                  justify-content-between
                  align-items-center
                " v-for="(v, k) in row.teamtaskuser" :key="index + '_' + k">
                {{ v.user.name }}
                <span class="badge badge-pill" v-text="['已经完成', '未查看', '已查看'][Number(v.type)]"></span>
              </li>
            </ul>
            <el-empty v-else description="没有成员"></el-empty>
          </template>
        </el-table-column>
        <el-table-column prop="ID" label="ID" width="80"> </el-table-column>
        <el-table-column prop="createdAt" :formatter="({ createdAt }) => TimeYH(createdAt)" label="创建时间" width="180">
        </el-table-column>
        <el-table-column prop="createdAt" :formatter="({ user }) => formatteruser(user)" label="创建者" width="180">
        </el-table-column>
        <el-table-column prop="context" label="内容"> </el-table-column>
        <el-table-column fixed="right" label="操作" width="100">
          <template #default="scope">
            <el-button @click="del(scope.row.ID)" text size="default">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="text-right" v-if="task?.count" style="margin-top:10px">
      <el-pagination @current-change="handleCurrentChange" :page-size="Number(limit)" layout="prev, pager, next"
        :total="task?.count"></el-pagination>
    </div>
    <el-empty class="col" v-if="!task?.count"
      image="https://cdn.hterobot.com/JOY/oj_1_1/Not%20Found%20illustration.png" />
  </div>
</template>


<script lang="ts">
import { Teamtask } from "../../../admin/views/data";
import { teamteskrules } from "../../../admin/views/data/formrules";
import {
  asyncteamcreateteamtask,
  asyncdelteamtask,
  asyncaddteamlog,
} from "../../../api";
import { ElForm, ElMenu, ElMessage, ElMessageBox } from "element-plus";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { TimeYH } from "../../../util/time";
import {
  computed,
  defineComponent,
  PropType,
  reactive,
  ref,
  toRaw,
  toRef,
  toRefs,
  watch,
} from "vue";
import { flatten, uniq, some } from "underscore";
import { Imyreq } from "../../../interface";
export default defineComponent({
  props: {
    data: {
      type: Object as PropType<Studycodemodel.Iteam>,
    },
    changeteam: {
      type: Function as PropType<(str: Studycodemodel.Iteam) => void>,
    },
    isAdmin: {
      type: Number as PropType<0 | 1 | 2>,
    },
    user: {
      type: Object as PropType<Studycodemodel.Iuser>,
    },
    teamusers: {
      type: Array as PropType<Studycodemodel.Iteamuser[]>,
    },
    task: {
      type: Object as PropType<Imyreq<Studycodemodel.Iteamtask>>,
    },
    gettask: Function,
  },
  setup(p) {
    const { user, teamusers, data } = toRefs(p);
    const ruleForm = reactive<Studycodemodel.Iteamtask>(
      Object.assign({}, Teamtask)
    );
    const offset = ref(0);
    const limit = ref(10);
    const dialogTableVisible = ref(false);
    const group = computed(() => {
      let n: Studycodemodel.Iteamusergroup[] = [];
      if (data?.value) {
        const g = data.value.teamusergroup || [];
        n = g.map((e) => {
          let children: any[] = [];
          if (teamusers?.value) {
            children = teamusers.value
              .filter((v) => v.teamusergroupid === e.ID)
              .map((v) => {
                const { user, userid } = v;
                return {
                  ...v,
                  label: user?.name,
                  value: userid,
                };
              });
          }
          return {
            ...e,
            children,
            value: 0,
            label: e.name,
          };
        });
      }
      const o: Studycodemodel.Iteamusergroup & {
        label?: string;
        children?: any;
      } = {
        name: "未分组",
        label: "未分组",
        children:
          p.teamusers
            ?.filter((e) => e.jurisdiction === "0" && !e.teamusergroupid)
            .map((e) => {
              return {
                ...e,
                label: e.user?.name,
                value: e.userid,
              };
            }) || [],
      };
      return [o].concat(n);
    });

    function handleCurrentChange(r: number) {
      offset.value = (r - 1) * 10;
    }

    function formatteruser(user: Studycodemodel.Iuser) {
      let name = user.name;
      if (p.teamusers) {
        const t = p.teamusers.find((e) => e.userid === user.ID);
        if (t) {
          name = t.user?.name;
        }
      }
      return name;
    }

    async function submitForm() {
      const v = ruleForm1.value;
      if (!v) return;
      v.validate(async (t: any) => {
        if (t) {
          const data = toRaw(ruleForm);
          const f = {
            ...data,
            users: uniq(flatten(data.teamtaskuser ? data.teamtaskuser : [])).filter((e) => e),
            teamid: p.data?.ID,
          };
          await asyncteamcreateteamtask(f);
          ElMessage.success("添加成功");
          await asyncaddteamlog({
            type: "任务",
            context: "创建任务",
            teamid: p.data?.ID,
            userid: p.user?.ID,
            username: p.user?.name,
          });
          if (p.gettask) p.gettask();
          dialogTableVisible.value = false;
        }
      });
    }

    function del(ID: number) {
      if (!p.isAdmin) {
        ElMessage.error("管理员才有权操作");
        return;
      }
      ElMessageBox.confirm("是否删除次任务", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
      }).then(() => {
        asyncdelteamtask({ ID })
          .then(() => {
            ElMessage.success("删除成功");
            if (p.gettask) p.gettask();
            asyncaddteamlog({
              type: "任务",
              context: "删除任务",
              teamid: p.data?.ID,
              userid: p.user?.ID,
              username: p.user?.name,
            });
          })
          .catch((E) => {
            ElMessage.error(E);
          });
      });
    }

    watch([offset], (e, r) => {
      if (p.gettask) p.gettask(offset.value);
    });

    const rules = teamteskrules;

    const ruleForm1 = ref<typeof ElForm>();

    return {
      dialogTableVisible,
      ruleForm,
      group,
      submitForm,
      rules,
      ruleForm1,
      offset,
      limit,
      handleCurrentChange,
      formatteruser,
      TimeYH,
      del,
    };
  },
});
</script>
